package com.fable.utils;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.UUID;

/**
 * Created by weishuai on 18/5/14.
 */
public class QiniuImgUtil {

    private static final Logger logger = LoggerFactory.getLogger(QiniuImgUtil.class);


    /**
     * 华东地区
     */
    private static Configuration cfg = new Configuration(Zone.zone0());
    private static UploadManager uploadManager = new UploadManager(cfg);

    private static String accessKey = "19aadND-sDJUAsuVLW-UUhDILGz7NSDnYwlr-KsI";
    private static String secretKey = "UJfCdu3VltFDFA8rwHL7xvtlrWnKKhfyO5UGLf4y";
    private static String bucket = "msrz";

    public static String upload(String userName,byte[] data, String fileName) {

        String result = "";
        DefaultPutRet putRet=null;
        try {
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            Response response = uploadManager.put(data, fileName, upToken);
            //解析上传成功的结果
            putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            result = putRet.key;
            logger.info("上传七牛成功,userName{},fileName:{},result:{}", userName,fileName, JSON.toJSONString(putRet));
        } catch (QiniuException e) {
            logger.error("上传七牛失败,userName:{},fileName:{},result:{}",userName,fileName, JSON.toJSONString(putRet),e);
        }
        return result;
    }

    public static void main(String[] args) {
        try {
            byte[] uploadBytes = "22122222".getBytes("utf-8");

            String key = QiniuImgUtil.upload("",uploadBytes, UUID.randomUUID().toString());
            System.out.println(key);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
